package com.css.dzj.dzjap.modules.record.approject.service.impl;

import com.css.dzj.dzjap.common.util.Constant;

import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.modules.info.service.ConstrService;
import com.css.dzj.dzjap.modules.publick.dao.PublicDao;
import com.css.dzj.dzjap.modules.publick.entity.ApPublicEntity;
import com.css.dzj.dzjap.modules.record.approject.entity.ApRecordEntity;

import com.css.dzj.dzjap.modules.record.approject.entity.QApRecordEntity;
import com.css.dzj.dzjap.modules.record.approject.mapper.ApRecordMapper;
import com.css.dzj.dzjap.modules.record.approject.service.ApRecordService;


import com.css.dzj.dzjap.modules.todolist.entity.ApTodoEntity;
import com.css.dzj.dzjap.modules.todolist.mapper.ApTodoMapper;
import com.css.dzj.dzjap.modules.todolist.service.ApTodoService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApRecordServiceImpl implements ApRecordService {
    @Autowired
    private ApRecordMapper apRecordMapper;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private ApTodoService apTodoService;
    @Autowired
    private PublicDao publicDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ApTodoMapper apTodoMapper;
    @Autowired
    private ConstrService constrService;

    @Override
    public Page<ApRecordEntity> getAllPage(Pageable pageable) {
        Page<ApRecordEntity> all = apRecordMapper.findAll(pageable);
        return all;
    }

    @Override
    public QueryResults<ApRecordEntity> getPage(String userName, String recordProjectName, String recordProjectType, String status,
                                                String recordUser, String recordTimeStart, String recordTimeEnd, String recordProjectAddress, String reportStatus, Pageable pageable) {
        QApRecordEntity q = QApRecordEntity.apRecordEntity;
        com.querydsl.core.types.Predicate predicate = q.isNotNull().or(q.isNull());


        // 多条件查询：项目名称、工程类别、状态、备案人员、备案申请开始时间、备案申请结束时间等
        if (!StringUtils.isEmpty(recordProjectAddress) && recordProjectAddress.contains("建设单位")) {
            String unitCode = constrService.findUnitCode(userName);
            predicate = ExpressionUtils.and(predicate, q.recordUnitCode.eq(unitCode));
        }
        if (!StringUtils.isEmpty(recordProjectAddress) && recordProjectAddress.contains("安评单位")) {
            predicate = ExpressionUtils.and(predicate, q.recordUser.eq(userName));
        }
        if (!StringUtils.isEmpty(recordProjectAddress) && recordProjectAddress.contains("中国")) {
            predicate = ExpressionUtils.and(predicate, q.reportStatus.eq(Constant.REPORT_STATUS_YES));
        }
        if (!StringUtils.isEmpty(recordProjectAddress) && !recordProjectAddress.contains("中国")
                && !recordProjectAddress.contains("安评单位") && !recordProjectAddress.contains("建设单位")) {
            predicate = ExpressionUtils.and(predicate, q.recordProjectAddress.like("%" + recordProjectAddress + "%"));
            predicate = ExpressionUtils.and(predicate, q.status.ne(Constant.CHECK_STATUS0));
        }
        predicate = (StringUtils.isEmpty(reportStatus)) ? predicate : ExpressionUtils.and(predicate, q.reportStatus.eq(reportStatus));
        predicate = (StringUtils.isEmpty(recordProjectName)) ? predicate : ExpressionUtils.and(predicate, q.recordProjectName.like("%" + recordProjectName + "%"));
        predicate = (StringUtils.isEmpty(recordProjectType)) ? predicate : ExpressionUtils.and(predicate, q.recordProjectType.like("%" + recordProjectType + "%"));
        predicate = (StringUtils.isEmpty(status)) ? predicate : ExpressionUtils.and(predicate, q.status.like("%" + status + "%"));
        predicate = (StringUtils.isEmpty(recordUser)) ? predicate : ExpressionUtils.and(predicate, q.recordUser.like("%" + recordUser + "%"));
        if ((StringUtils.isEmpty(recordTimeStart)) && (!StringUtils.isEmpty(recordTimeEnd))) {
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(recordTimeEnd + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.loe(endDate));
        }
        if ((!StringUtils.isEmpty(recordTimeStart)) && (StringUtils.isEmpty(recordTimeEnd))) {
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(recordTimeStart+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.goe(startDate));
        }
        if ((!StringUtils.isEmpty(recordTimeStart)) && (!StringUtils.isEmpty(recordTimeEnd))) {
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(recordTimeStart+" "+"00:00:00.000");
                endDate = sf.parse(recordTimeEnd+" "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.between(startDate, endDate));
        }
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));

        return jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(
                        // 根据创建日期，降序排序
                        q.createTime.desc()
                )
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();

    }

    @Override
    @Transactional
    public void save(ApRecordEntity apRecordEntity) {
        // 状态初始化
        //已提交未审核
        apRecordEntity.setStatus(Constant.CHECK_STATUS1);
        //未上报
        apRecordEntity.setReportStatus(Constant.REPORT_STATUS_NO);
        //未抽取
        apRecordEntity.setRecordExtractStauts(Constant.UNEXTRACT);
        //未拟办公告
        apRecordEntity.setRecordPublicStauts(Constant.PUBLICNO);
        apRecordEntity.setExtractPublicStatus(Constant.PUBLICNO);
        apRecordEntity.setDelFlag(Constant.NO_DELETE);
        apRecordEntity.setCreateTime(new Date());
        apRecordMapper.save(apRecordEntity);
     /*   //查询待办里有没有此业务暂存
        ApTodoEntity apTodoEntity=apTodoService.findByIdandType(apRecordEntity.getRecordId(),Constant.TYPEFLAGZC);
        if(apTodoEntity!=null){
            //此暂存业务已办
            apTodoEntity.setStatus(Constant.STATUSYB);
            apTodoService.update(apTodoEntity);
        }*/
        //调取待办接口
        ApTodoEntity apTodoEntity = new ApTodoEntity();
        apTodoEntity.setStatus(Constant.STATUSDB);
        apTodoEntity.setCreateTime(new Date());
        apTodoEntity.setDelFlag(Constant.NO_DELETE);
        apTodoEntity.setTitle(apRecordEntity.getRecordProjectName() + "安评项目备案审批");
        apTodoEntity.setLinkId(apRecordEntity.getRecordId());
        //审批员才能看到相应的审批
        apTodoEntity.setStation("项目审核员");
        //去审批页
        apTodoEntity.setUrl("../todolist/prorecord.html");
        apTodoEntity.setLocation(apRecordEntity.getRecordProjectAddress());
        apTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
        //审批的业务
        apTodoEntity.setTypeFlag(Constant.TYPRFLAGSS);
        apTodoService.saveDB(apTodoEntity);
    }

    @Override
    @Transactional
    public void zcsave(ApRecordEntity apRecordEntity) {
        // 状态初始化
        //未提交
        apRecordEntity.setStatus(Constant.CHECK_STATUS0);
        //未上报
        apRecordEntity.setReportStatus(Constant.REPORT_STATUS_NO);
        //未抽取
        apRecordEntity.setRecordExtractStauts(Constant.UNEXTRACT);
        //未拟办公告
        apRecordEntity.setRecordPublicStauts(Constant.PUBLICNO);
        apRecordEntity.setDelFlag(Constant.NO_DELETE);
        apRecordEntity.setCreateTime(new Date());

        apRecordEntity.setExtractPublicStatus(Constant.PUBLICNO);
        apRecordMapper.save(apRecordEntity);
    /*    //查询待办里有没有此业务暂存
        ApTodoEntity apTodoEntity=apTodoService.findByIdandType(apRecordEntity.getRecordId(),Constant.TYPEFLAGZC);
        if(apTodoEntity==null) {
            //调取待办接口
            apTodoEntity = new ApTodoEntity();
            apTodoEntity.setStatus(Constant.STATUSDB);
            apTodoEntity.setCreateTime(new Date());
            apTodoEntity.setDelFlag(Constant.NO_DELETE);
            apTodoEntity.setTitle(apRecordEntity.getRecordProjectName() + "安评项目备案暂存");
            apTodoEntity.setLinkId(apRecordEntity.getRecordId());
            //去提交页
            apTodoEntity.setUrl("/aprecord/update");
            apTodoEntity.setLocation(apRecordEntity.getRecordProjectAddress());
            //暂存的业务
            apTodoEntity.setTypeFlag(Constant.TYPEFLAGZC);
            //创建人，暂存只能看到自己的信息。
            apTodoEntity.setCreatePerson("111");
            apTodoService.saveDB(apTodoEntity);
        }*/
    }

    @Override
    public ApRecordEntity queryApRecordById(String id) {
        ApRecordEntity apRecordEntity = apRecordMapper.findById(id).get();
        return apRecordEntity;
    }

    @Override
    public void update(ApRecordEntity apRecordEntity) {
    }

    @Override
    public void check(ApRecordEntity apRecordEntity) {
        //更新安评备案审批内容
        update(apRecordEntity);
        //查询待办里有没有此业务审批
        ApTodoEntity apTodoEntity = apTodoService.findByIdandType(apRecordEntity.getRecordId(), Constant.TYPRFLAGSS);
        if (apTodoEntity != null) {
            apTodoEntity.setStatus(Constant.STATUSYB);
            apTodoService.update(apTodoEntity);
        }
    }
    @Override
    public void cancel(ApRecordEntity apRecordEntity) {
        //更新安评备案审批内容
        update(apRecordEntity);
        //查询待办里有没有此业务审批
        ApTodoEntity apTodoEntity = apTodoService.findByIdandType(apRecordEntity.getRecordId(), Constant.TYPRFLAGSS);
        if (apTodoEntity != null) {
            apTodoMapper.delete(apTodoEntity);
        }
    }

    @Override
    public List<ApRecordEntity> getApRecordListByRecordLevel(String location, String recordLevel) {
        QApRecordEntity qApRecordEntity = QApRecordEntity.apRecordEntity;
        List<ApRecordEntity> list = new ArrayList<ApRecordEntity>();
        if (!StringUtils.isEmpty(location) && location.contains(Constant.LOCATIONZG)) {
            list = jpaQueryFactory.selectFrom(qApRecordEntity).where(qApRecordEntity.recordLevel.eq(recordLevel),
                    qApRecordEntity.delFlag.eq(Constant.NO_DELETE), qApRecordEntity.status.eq(Constant.CHECK_STATUS3), qApRecordEntity.recordProjectType.ne("0").and(qApRecordEntity.recordProjectType.ne("1"))).fetch();
        }
        if (!StringUtils.isEmpty(location) && !location.contains(Constant.LOCATIONZG)) {
            list = jpaQueryFactory.selectFrom(qApRecordEntity).where(qApRecordEntity.recordLevel.eq(recordLevel),
                    qApRecordEntity.delFlag.eq(Constant.NO_DELETE), qApRecordEntity.status.eq(Constant.CHECK_STATUS3), qApRecordEntity.recordProjectAddress.like("%" + location + "%"), qApRecordEntity.recordProjectType.ne("0").and(qApRecordEntity.recordProjectType.ne("1"))).fetch();
        }

        return list;
    }

    @Override
    public void submit(ApRecordEntity apRecordEntity) {
        //更新安评备案审批内容
        update(apRecordEntity);
       /* //查询待办里有没有此业务暂存
        ApTodoEntity apTodoEntity=apTodoService.findByIdandType(apRecordEntity.getRecordId(),Constant.TYPEFLAGZC);
        if(apTodoEntity!=null){
            apTodoEntity.setStatus(Constant.STATUSYB);
            apTodoService.update(apTodoEntity);
        }*/

        //调取待办接口
        ApTodoEntity apTodoEntity = new ApTodoEntity();
        apTodoEntity.setStatus(Constant.STATUSDB);
        apTodoEntity.setCreateTime(new Date());
        apTodoEntity.setDelFlag(Constant.NO_DELETE);
        apTodoEntity.setTitle(apRecordEntity.getRecordProjectName() + "安评项目备案审批");
        apTodoEntity.setLinkId(apRecordEntity.getRecordId());
        //审批员才能看到相应的审批
        apTodoEntity.setStation("项目审核员");
        //去审批页
        apTodoEntity.setUrl("../todolist/prorecord.html");
        apTodoEntity.setLocation(apRecordEntity.getRecordProjectAddress());
        apTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
        //审批的业务
        apTodoEntity.setTypeFlag(Constant.TYPRFLAGSS);
        apTodoService.saveDB(apTodoEntity);
    }

    @Override
    public QueryResults<ApRecordEntity> getShPage(String recordProjectName, String recordProjectType, String status,
                                                  String recordUser, String recordTimeStart, String recordTimeEnd, String recordProjectAddress, String reportStatus, Pageable pageable) {
        QApRecordEntity q = QApRecordEntity.apRecordEntity;
        com.querydsl.core.types.Predicate predicate = q.isNotNull().or(q.isNull());

        if (!StringUtils.isEmpty(recordProjectAddress) && recordProjectAddress.contains(Constant.LOCATIONZG)) {
            predicate = ExpressionUtils.and(predicate, q.reportStatus.eq(Constant.REPORT_STATUS_YES));
        }
        if (!StringUtils.isEmpty(recordProjectAddress) && !recordProjectAddress.contains(Constant.LOCATIONZG)) {
            predicate = ExpressionUtils.and(predicate, q.recordProjectAddress.like("%" + recordProjectAddress + "%"));
            predicate = ExpressionUtils.and(predicate, q.status.eq(Constant.CHECK_STATUS3));
        }
        predicate = (StringUtils.isEmpty(reportStatus)) ? predicate : ExpressionUtils.and(predicate, q.reportStatus.eq(reportStatus));
        predicate = (StringUtils.isEmpty(recordProjectName)) ? predicate : ExpressionUtils.and(predicate, q.recordProjectName.like("%" + recordProjectName + "%"));
        predicate = (StringUtils.isEmpty(recordProjectType)) ? predicate : ExpressionUtils.and(predicate, q.recordProjectType.like("%" + recordProjectType + "%"));
        predicate = (StringUtils.isEmpty(status)) ? predicate : ExpressionUtils.and(predicate, q.status.like("%" + status + "%"));
        predicate = (StringUtils.isEmpty(recordUser)) ? predicate : ExpressionUtils.and(predicate, q.recordUser.like("%" + recordUser + "%"));
        if ((StringUtils.isEmpty(recordTimeStart)) && (!StringUtils.isEmpty(recordTimeEnd))) {
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(recordTimeEnd + " "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.loe(endDate));
        }
        if ((!StringUtils.isEmpty(recordTimeStart)) && (StringUtils.isEmpty(recordTimeEnd))) {
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(recordTimeStart+" "+"00:00:00.000");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.goe(startDate));
        }
        if ((!StringUtils.isEmpty(recordTimeStart)) && (!StringUtils.isEmpty(recordTimeEnd))) {
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(recordTimeStart+" "+"00:00:00.000");
                endDate = sf.parse(recordTimeEnd+" "+"23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.recordTime.between(startDate, endDate));
        }
        predicate = ExpressionUtils.and(predicate, q.recordProjectType.eq("0").or(q.recordProjectType.eq("1")));
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));

        return jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(
                        // 根据创建日期，降序排序
                        q.createTime.desc()
                )
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
    }

    @Override
    @Transactional
    public String addHandle(ApPublicEntity pub) {
        pub.setCreateUser(ServiceUtil.getLoginName(request));
        pub.setOrganName(ServiceUtil.getOrgName(request));
        pub.setRevokeg(Constant.REVOKE_NO);
        pub.setDelFlag(Constant.NO_DELETE);
        pub.setCreateTime(new Date());
        pub.setInputenTime(new Date());
        pub.setPublicUrl("/dzjap/aprecord/getAprecord");
        //公开公告状态为：5
        pub.setFictionType("5");
        //公开业务类型为：安评成果备案拟办
        pub.setEnterType("5");
        try {
            publicDao.save(pub);

            //调取待办接口
            ApTodoEntity apTodoEntity = new ApTodoEntity();
            apTodoEntity.setStatus(Constant.STATUSDB);
            apTodoEntity.setCreateTime(new Date());
            apTodoEntity.setDelFlag(Constant.NO_DELETE);
            apTodoEntity.setTitle(pub.getTitle() + "公开公告审批");
            apTodoEntity.setLinkId(pub.getPublicId());
            //审批员才能看到相应的审批
            apTodoEntity.setStation("地震部门审定人员");
            //去审批页
            apTodoEntity.setUrl("../todolist/publick.html");
            apTodoEntity.setLocation(pub.getOrganName());
            apTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
            //审批的业务
            apTodoEntity.setTypeFlag(Constant.TYPRFLAGSS);
            apTodoService.saveDB(apTodoEntity);


            //修改安评单位成果状态为已拟办
            ApRecordEntity apRecordEntity = queryApRecordById(pub.getRelationId());
            apRecordEntity.setRecordPublicStauts(Constant.PUBLICYES);
            update(apRecordEntity);
            return pub.getPublicId();
        } catch (Exception e) {
            return "0";
        }
    }

    @Override
    public void updatestatus(String id) {
        ApRecordEntity targetApRecordEntity = queryApRecordById(id);
        //已抽取
        targetApRecordEntity.setRecordExtractStauts(Constant.EXTRACT);
        targetApRecordEntity.setUpdateTime(new Date());
        update(targetApRecordEntity);
    }

    @Override
    public ApRecordEntity queryByProName(String proName) {
        if (!StringUtils.isEmpty(proName)) {
            QApRecordEntity q = QApRecordEntity.apRecordEntity;
            return jpaQueryFactory.selectFrom(q).where(q.recordProjectName.eq(proName), q.delFlag.eq(Constant.NO_DELETE)).fetchOne();
        }
        return null;
    }

    /**
     * 获取所有审核通过的涉核和国家水电项目 --- 开展监管工作情况
     * @return
     */
    @Override
    public QueryResults<ApRecordEntity> findAll(Pageable pageable) {
        QApRecordEntity q = QApRecordEntity.apRecordEntity;
        return jpaQueryFactory.selectFrom(q)
                .where(q.recordProjectType.eq("0").or(q.recordProjectType.eq("1")), q.status.eq(Constant.CHECK_STATUS3), q.delFlag.eq(Constant.NO_DELETE))
                .orderBy(q.createTime.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();

    }
    @Override
    public List queryAllRecord(){
        QApRecordEntity q = QApRecordEntity.apRecordEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE)) ;
        List<ApRecordEntity> list = jpaQueryFactory.selectFrom(q)
                .where(predicate)
                .orderBy(q.createTime.desc())
                .fetch();
        return list;
    }
}
